/*
 * @Author: Ac
 * @LastEditors: Please set LastEditors
 * @Description: 
 */
import { ref, unref, reactive } from 'vue';
import { pickBy } from "lodash-es";
import { ElMessage, ElMessageBox } from 'element-plus'
import { request } from "@/apis/request";

function useListView(listFilter, visible = true) {
  // const pageOptions = reactive({ pageIndex: 1, pageSize: 10, total: 0, layout: "total, slot, ->, prev, pager, next,sizes,jumper" });
  let filterData = ref({});
  let filterVisible = ref(visible);
  let queryTableData = null;
  let pageOptions = {
    pageIndex: 0,
    pageSize: 0
  };

  function setQueryMethod(query) {
    queryTableData = query;
  }

  function setPageOptions(po) {
    pageOptions = po
  }

  function handleCurrentPageChange(pageIndex) {
    pageOptions.pageIndex = pageIndex;
    queryTableData();
  }
  function handlePageSizeChange(pageSize) {
    pageOptions.pageSize = pageSize;
    pageOptions.pageIndex = 1;
    queryTableData();
  }
  function handleSearchListView(data = {}) {
    pageOptions.pageIndex = 1;
    pageOptions.pageSize = 10;
    filterData.value = {}
    Object.assign(filterData.value, pickBy(data, (val) => !['', null, undefined].includes(val)))
    queryTableData();
  }
  function resetListView() {
    unref(listFilter).resetListView();
  }
  function searchListView() {
    listFilter.sSearchListView();
  }
  function handleToggleFilterOfListView() {
    filterVisible.value = !filterVisible.value
  }
  /**
   * @description: 删除列表项
   * @param {object} params 接口参数
   * 默认值{ url: '', method: 'delete', data: { } }
   * @param {string} type 值：''|'batch'
   * 'batch'表示批量删除，默认值''表示单个删除
   * @return {*}
   */
  function deleteItemOfListView(params = { url: '', method: 'delete', data: {} }, type = '') {
    ElMessageBox.confirm(
      type === 'batch' ? "确认删除选中项？" : "确认删除该项？",
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
      .then(() => {
        request(params)
          .then(() => {
            resetListView();
          })
          .catch(error => console.error(error.message));
      }).catch(() => {
        // catch cancel
      })
  }

  return {
    pageOptions,
    filterData,
    filterVisible,
    searchListView,
    resetListView,
    setQueryMethod,
    setPageOptions,
    handleSearchListView,
    deleteItemOfListView,
    handlePageSizeChange,
    handleCurrentPageChange,
    handleToggleFilterOfListView
  }
}


export default useListView;